package pages;

import java.util.Random;

import objects.Movie;
import objects.User;

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.Select;

import testBase.TestBase;


public class Page extends TestBase{

	private static Random rnd = new Random();
	
	
	public static void login() {
		LoginPage.userNameField.clear();
		LoginPage.userNameField.sendKeys("admin");
		LoginPage.passwordField.clear();
		LoginPage.passwordField.sendKeys("admin");
		LoginPage.loginButton.click();
	}
	
	public static void logout() {
	InternalPage.menuLogoutLink.click();
	}
	
	public static void clickUserManagement() {
		InternalPage.UserManagementLink.click();
		
	}
	
	public static void clickHome() {
		InternalPage.homeLink.click();
		
	}
	
	public static String generatePassword() {
		String pass = "" + rnd.nextInt(100)
						 + (char)(rnd.nextInt(26) + 'a')
						 + (char)(rnd.nextInt(26) + 'a')
						 + (char)(rnd.nextInt(26) + 'a');
		return pass;
	}
	

	public static void createRandomUser(User user) {
		String password = generatePassword();
		UserManagmentPage.userNameField.sendKeys(user.getName());
		UserManagmentPage.emailField.sendKeys(user.getEmail());
		UserManagmentPage.passwordField.sendKeys(password);
		UserManagmentPage.passwordAgainField.sendKeys(password);
		new Select(UserPage.select).selectByValue(user.getRole());
		UserManagmentPage.saveButton.click();
	}
	
	public static void createRandomMovie(Movie movie) {
		HomePage.addMovie.click();
		MoviePage.titleFill.sendKeys(movie.getTitle());
		MoviePage.yearFill.sendKeys(movie.getYear());
		MoviePage.saveButton.click();
		String id = driver.getCurrentUrl().replace("http://localhost/php4dvd/?go=movie&id=", "");
		movie.setId(id);
	}
	

	public static Movie movieModify(Movie movie, Movie newMovie) {
		HomePage.videoPageClick(movie.getId());
		MoviePage.editMovieClick(movie.getId());
		MoviePage.titleFill.clear();
		MoviePage.titleFill.sendKeys(newMovie.getTitle());
		MoviePage.yearFill.clear();
		MoviePage.yearFill.sendKeys(newMovie.getYear());
			newMovie.setId((movie.getId()));
		MoviePage.saveButton.click();
		return newMovie;
	}
	

	public static User userModify(User user, User newUser) {
		String password = generatePassword();
		UserManagmentPage.userTable.findElement(By.cssSelector("a[href='./?go=user&id=" + user.getId() + "']")).click();
		UserPage.emailField.clear();
		UserPage.emailField.sendKeys(newUser.getEmail());
		UserPage.passwordField.sendKeys(password);
		UserPage.passwordAgainField.sendKeys(password);
		new Select(UserPage.select).selectByValue(newUser.getRole());
			String userName = user.getName();
			newUser.setName(userName);
		UserPage.saveButton.click();
		return newUser;
	}
	
}
